package cn.txy.system.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.txy.base.service.impl.BaseServiceImpl;
import cn.txy.config.R;
import cn.txy.system.domain.Employee;
import cn.txy.system.domain.Logininfo;
import cn.txy.system.domain.Menu;
import cn.txy.system.mapper.LogininfoMapper;
import cn.txy.system.mapper.MenuMapper;
import cn.txy.system.service.LogininfoService;
import cn.txy.system.utils.JwtUtil;
import cn.txy.system.utils.Payload;
import cn.txy.system.vo.LogininfoVo;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public R login(LogininfoVo logininfoVo) {
        if (StringUtils.isEmpty(logininfoVo.getUsername())){
            return R.fail("用户名不能为空");
        }
        if (StringUtils.isEmpty(logininfoVo.getPassword())){
            return R.fail("密码不能为空");
        }
        if (logininfoVo.getType() != 0){
            return R.fail("您不是管理者，无法登录");
        }
        //根据账号名和type查数据，需要new一个loginInfo
        Logininfo logininfo = logininfoMapper.findLogininfoByUserNameAndType(logininfoVo);
        if (logininfo ==null){
            return R.fail("账号密码错误");
        }
        //通过数据和密码 查询出来的盐值加密
        String salt = logininfo.getSalt() + logininfoVo.getPassword();
        String newPwd = SecureUtil.md5(salt);
        //判断和数据库的密码是否一致
        if (!logininfo.getPassword().equals(newPwd)){
            //不存在
            R.fail("账号或密码错误");
        }
        //存在 生成token和[权限，菜单，信息]
        Payload payload = new Payload();
        payload.setLogininfo(logininfo);
        String token = JwtUtil.generateToken(payload);
        // key   value
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //获取[权限，菜单]
        if (logininfoVo.getType() == 0){
            //logininfo_id  employee_id  permission_id  menu_id
            //logininfo_id
            Long id = logininfo.getId();
            //employee_id
            Employee employee = logininfoMapper.findEmployeeByInfoId(id);
            if (employee != null) {
                payload.setEmployee(employee);
                map.put("userinfo", employee);
                //permission_id
                List<String> permissions = logininfoMapper.findPerByEmpId(employee.getId());
                payload.setPermissions(permissions);
                map.put("permissions", permissions);
                //menu_id
                List<Menu> menus = logininfoMapper.findMenuByEmpId(employee.getId());
//差父级
                List<Long> meunpid = menus.stream().map(Menu::getParentId).distinct().collect(Collectors.toList());
                List<Menu> menusP =menuMapper.findIds(meunpid);
                menus.addAll(menusP);

                List<Menu> menusTree = menusTree(menus);
                payload.setMenus(menusTree);
                map.put("menus", menusTree);
            }
        }
        return R.ok(map);
    }

    public static List<Menu> menusTree(List<Menu> menus) {
        if (menus == null) {
            return null;
        }
        // 使用 HashSet 去重
        Set<Menu> menuSet = new HashSet<>(menus);
        List<Menu> uniqueMenus = new ArrayList<>(menuSet);

        Map<Long, Menu> map = uniqueMenus.stream()
                .collect(Collectors.toMap(Menu::getId, menu -> menu));

        List<Menu> result = new ArrayList<>();

        for (Menu menu : uniqueMenus) {
            if (menu.getParentId() == null) {
                result.add(menu);
            } else {
                Menu pmenu = map.get(menu.getParentId());
                pmenu.getChildren().add(menu);
            }
        }
        return result;
        }
    }

